package com.atlin.project.manager.factory;

import com.atlin.project.model.domain.SysLogininfo;
import com.atlin.project.model.domain.SysOperLog;
import com.atlin.project.service.SysOperLogService;
import com.atlin.project.service.impl.SysLogininfoServiceImpl;
import com.atlin.project.utils.*;
import com.atlin.project.utils.ip.AddressUtils;
import com.atlin.project.utils.ip.NetUtils;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;

import java.util.Date;
import java.util.TimerTask;

/**
 * 异步工厂（产生异步任务用）
 *
 * @author atlin
 */
@Slf4j
public class AsyncFactory {

    /**
     * 记录登录信息
     *
     * @param sysLogininfo 登录信息
     * @param args         列表
     * @return 任务task
     */
    public static TimerTask recordSysLogininfo(final SysLogininfo sysLogininfo, final Object... args) {
        return new TimerTask() {
            @Override
            public void run() {
                // 计时
                StopWatch stopWatch = new StopWatch();
                stopWatch.start();

                String address = AddressUtils.getRealAddressByIP(sysLogininfo.getIpaddr());
                sysLogininfo.setLoginLocation(address);

                StringBuilder s = new StringBuilder();
                s.append(LogUtils.getBlock(sysLogininfo.getIpaddr()));
                s.append(LogUtils.getBlock(address));
                s.append(LogUtils.getBlock(sysLogininfo.getUserAccount()));
                s.append(LogUtils.getBlock(sysLogininfo.getStatus()));

                //插入数据
                SpringContextUtils.getBean(SysLogininfoServiceImpl.class).save(sysLogininfo);
                stopWatch.stop();
                s.append(LogUtils.getBlock("cost", stopWatch.getTotalTimeMillis(), "ms"));
                // 打印信息到日志
                log.info(s.toString(), args);
            }
        };
    }

    /**
     * 操作日志记录
     *
     * @param operLog 操作日志信息
     * @return task任务
     */
    public static TimerTask recordOper(final SysOperLog operLog) {
        return new TimerTask() {
            @Override
            public void run() {
                // 远程查询操作地点
                operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
                SpringContextUtils.getBean(SysOperLogService.class).save(operLog);
            }
        };
    }
}
